package com.trainmodel.eu.z21helper;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class EmulatorSide implements Runnable {

	private String localEmulatorHost = "127.0.0.1";

	private int emulatorPort = -1;
	private int localEmulatorPort = 21105;

	private CenterSide centerSide = null;

	private InetAddress emulatorAddress;
	private DatagramSocket emulatorSocket;

	private Z21Helper z21helper = null;

	public void sendToEmulator(DatagramPacket packet) {
		try {
			if (emulatorAddress != null && emulatorSocket != null) { // test if initialized
				packet.setAddress(emulatorAddress);
				packet.setPort(emulatorPort);
				emulatorSocket.send(packet);
			}
		} catch (Exception e) {
			if (z21helper != null)
				z21helper.errorAndQuit("Unable to sent packet to emulator.\n\n" + e.getMessage());
		}
	}

	@Override
	public void run() {
		try {
			emulatorSocket = new DatagramSocket(localEmulatorPort, InetAddress.getByName(localEmulatorHost));
			while (true) {
				DatagramPacket p = new DatagramPacket(new byte[2500], 2500);
				emulatorSocket.receive(p);
				if (emulatorAddress == null) {
					emulatorAddress = p.getAddress();
					emulatorPort = p.getPort();
				}
				centerSide.sendToCenter(p);
			}

		} catch (Exception e) {
			if (z21helper != null)
				z21helper.errorAndQuit("Unable to open socket to communicate with emulator.\nIs one Z21 Helper already running? Close it and start again.\n\n"
						+ e.getMessage());
		}
	}

	public String getLocalEmulatorHost() {
		return localEmulatorHost;
	}

	public void setLocalEmulatorHost(String localEmulatorHost) {
		this.localEmulatorHost = localEmulatorHost;
	}

	public int getEmulatorPort() {
		return emulatorPort;
	}

	public void setEmulatorPort(int emulatorPort) {
		this.emulatorPort = emulatorPort;
	}

	public int getLocalEmulatorPort() {
		return localEmulatorPort;
	}

	public void setLocalEmulatorPort(int localEmulatorPort) {
		this.localEmulatorPort = localEmulatorPort;
	}

	public CenterSide getCenterSide() {
		return centerSide;
	}

	public void setCenterSide(CenterSide centerSide) {
		this.centerSide = centerSide;
	}

	public InetAddress getEmulatorAddress() {
		return emulatorAddress;
	}

	public Z21Helper getZ21helper() {
		return z21helper;
	}

	public void setZ21helper(Z21Helper z21helper) {
		this.z21helper = z21helper;
	}
}
